package com.keymozy.controller;

import com.keymozy.annotaion.NoAuthentication;
import com.keymozy.pojo.Staff;
import com.keymozy.pojo.dto.UpdPwd;
import com.keymozy.service.LoginService;
import com.keymozy.service.PositionService;
import com.keymozy.state.Code;
import com.keymozy.state.RespData;
import com.keymozy.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@CrossOrigin
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private PositionService positionService;

    @PostMapping("/login")
    public RespData login(HttpServletResponse resp,HttpServletRequest req, @RequestBody Staff staff){
        log.info(req.getRemoteAddr()+"：进入了login接口");

        HttpSession session = req.getSession();
        //得到token
        String token = loginService.login(staff.getPhone(),staff.getPsw());
        if (token!=null || !"".equals(token)){
            Cookie cookie = new Cookie("token", token);
            resp.addCookie(cookie);
            log.info("token:"+token.substring(0,6));
            session.setAttribute("isLogin",token.split("\\.")[1]);
            System.out.println("????:"+req.getRemoteHost());
            TokenUtil.ipLogin.put(req.getRemoteAddr(),token.split("\\.")[1]);
            return new RespData(Code.SUCCESS_LOGIN,null);
        }
        log.info("登录失败");
        return new RespData(Code.FALSE_LOGIN,null);
    }
    @PostMapping("/upd")
    public String updPwd(@RequestBody UpdPwd updPwd){
        return loginService.modifyPsw(updPwd);
    }
    @PutMapping("/upd")
    public String updUserMsg(@RequestBody UpdPwd updPwd){
        return loginService.updUserMsg(updPwd);
    }
    @PostMapping("/register")
    @NoAuthentication
    public RespData register(@RequestBody Staff staff){
        return new RespData(Code.SUCCESS_ADD_1,loginService.register(staff));
    }
}
